import yaml
import logging
from pathlib import Path

class ConfigLoader:
    def __init__(self, config_path):
        self.config_path = config_path
        self.config = self.load_config()

    def load_config(self):
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except Exception as e:
            logging.error(f"加载配置文件失败: {str(e)}")
            return {}

    def get_wx_alert_config(self):
        """获取企业微信告警配置"""
        wx_config = self.config.get('wx_alert', {})
        return {
            'webhook': wx_config.get('webhook', ''),
            'retry': wx_config.get('retry', 3),
            'timeout': wx_config.get('timeout', 5)
        }

    def get_database_config(self):
        """获取数据库配置"""
        db_config = self.config.get('database', {})
        pool_config = db_config.get('pool', {})
        return {
            'status_db': db_config.get('status_db', ''),
            'min_connections': pool_config.get('min_connections', 1),
            'max_connections': pool_config.get('max_connections', 5),
            'timeout': pool_config.get('timeout', 30)
        }

    def get_logging_config(self):
        """获取日志配置"""
        log_config = self.config.get('logging', {})
        return {
            'level': log_config.get('level', 'INFO'),
            'format': log_config.get('format', '%(asctime)s - %(levelname)s - %(message)s'),
            'file': log_config.get('file', '')
        }

    def parse_oracle_config(self, filepath):
        """解析Oracle数据库配置文件"""
        groups = {}
        current_group = ''
        
        try:
            with open(filepath) as f:
                for line in f:
                    line = line.strip()
                    if line.startswith('Group:'):
                        current_group = line.split(': ')[1]
                        groups[current_group] = []
                    elif line and ':' in line:
                        parts = line.split(':')
                        conn_str = parts[1].split('@')
                        user_pass = conn_str[0].split('/')
                        host_service = conn_str[1].split('/')
                        
                        groups[current_group].append({
                            'name': parts[0],
                            'user': user_pass[0],
                            'password': user_pass[1],
                            'host': host_service[0],
                            'service': host_service[1]
                        })
            return groups
        except Exception as e:
            logging.error(f"解析Oracle配置文件失败: {str(e)}")
            return {}